import React from 'react';
import { Table, Balloon, DatePicker } from '@teamix/ui';
import { YunxiaoIcon, ButtonIcon } from '@alife/devops-ui';
import Wcontainer from '@alife/aisc-widgets/lib/Wcontainer';
import Wline from '@alife/aisc-widgets/lib/Wline';
import Wlinebar from '@alife/aisc-widgets/lib/Wlinebar';
import dayjs from 'dayjs';
import ListLoading from 'atComponents/ListLoading';
import utils from 'utils';
import docs from 'utils/docs';
import intl from '../../../../../../../locale';

const prefix = 'project-statistics';
export default class MrInfo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      rangeTmp: [props.mr_start_time, props.mr_end_time],
    };
  }

  onRangePickerOk = (range) => {
    if (!range || !range.length) {
      return;
    }
    this.props.updateStatisticsData({
      mr_start_time: range[0],
      mr_end_time: range[1],
    });

    this.props.getTotalMrData();
    this.props.getDetailMrData();
    this.props.getCommentSummaryData();
  };

  getDateArr = (start, end) => {
    const arr = [start];
    let temp = start;
    while (dayjs(temp).isBefore(dayjs(end))) {
      temp = dayjs(temp).add(1, 'day').format('YYYY-MM-DD');
      arr.push(temp);
    }
    return arr;
  };

  getDetailInfo = (daily_detail, key) => {
    if (!daily_detail) {
      return [];
    }
    // 将每天的数据都显示出来，没有就填0
    const { mr_start_time, mr_end_time } = this.props;
    const dateArr = this.getDateArr(mr_start_time, mr_end_time);

    return dateArr.map((date) => {
      const daily_detail_info = daily_detail.find((item) => {
        return dayjs(item.date).format('YYYY-MM-DD') === date;
      });
      return [date, daily_detail_info ? daily_detail_info[key] : 0];
    });
  };

  onPersonalCRSort = (dataIndex, order) => {
    this.props.doPersonalCRSort({
      key: dataIndex,
      order,
    });
  };

  renderTip = () => {
    return (
      <div className="insight-git-repo-tip">
        <YunxiaoIcon type="task-line" className="tip-icon" />
        <span>
          {intl.get({
            id: 'code-assets.projectInsight.containers.mrInfo.TipHowToImproveThe',
            defaultMessage: 'Tip：如何提升合入代码的质量？',
          })}
        </span>
        &nbsp;&nbsp;
        <a href={docs('insight-mr')} target="_blank" rel="noreferrer">
          {intl.get({
            id: 'code-assets.projectInsight.containers.mrInfo.ToSee',
            defaultMessage: '去看看',
          })}
        </a>
      </div>
    );
  };

  disabledDate = (date) => {
    const { rangeTmp } = this.state;
    let yearLimit = false;
    if (rangeTmp && rangeTmp.length > 1) {
      const [start, end] = rangeTmp;
      yearLimit =
        (end && date.valueOf() < dayjs(end).subtract(1, 'year').valueOf()) ||
        (start && date.valueOf() > dayjs(start).add(1, 'year').valueOf());
    }
    return date.valueOf() > dayjs().valueOf() || yearLimit;
  };

  render() {
    const {
      mr_start_time,
      mr_end_time,
      isLoadingTotalMr,
      isLoadingDetailMr,
      detail_mr,
      comment_summary,
      total_mr,
    } = this.props;

    if (isLoadingTotalMr || !total_mr) {
      return <ListLoading className="project-content-loading" />;
    }
    const reviewDatas = [
      {
        name: intl.get({
          id: 'code-assets.projectInsight.containers.mrInfo.NewSubmittedTimes',
          defaultMessage: '新增提交次数',
        }),
        data: this.getDetailInfo(total_mr.daily_detail, 'commits_count'),
      },

      {
        name: intl.get({
          id: 'code-assets.projectInsight.containers.mrInfo.NewlyAddedOnTheSame',
          defaultMessage: '(当日新增中) 经过评审的提交次数',
        }),
        data: this.getDetailInfo(total_mr.daily_detail, 'review_commits_count'),
      },
    ];

    const commentData = [
      {
        name: intl.get({
          id: 'code-assets.projectInsight.containers.mrInfo.NumberOfChangedRows',
          defaultMessage: '改动行数',
        }),
        type: 'bar',
        yAxis: 1,
        data: comment_summary ? this.getDetailInfo(comment_summary.daily_detail, 'line_count') : [],
      },

      {
        name: intl.get({
          id: 'code-assets.projectInsight.containers.mrInfo.Comments',
          defaultMessage: '评论数',
        }),
        type: 'line',
        data: comment_summary
          ? this.getDetailInfo(comment_summary.daily_detail, 'comment_count')
          : [],
      },
    ];

    const totalCommitsPercent =
      total_mr.commits_count === 0
        ? 0
        : Math.round((total_mr.review_commits_count / total_mr.commits_count) * 100);

    return (
      <div className={`${prefix}`}>
        <section className={`${prefix}-mr-overview`}>
          <div className={`${prefix}-mr-overview-title`}>
            <div className={`${prefix}-mr-overview-title-time`}>
              {this.renderTip()}
              <div className="range">
                <DatePicker.RangePicker
                  followTrigger
                  popupAlign="tr br"
                  onOk={this.onRangePickerOk}
                  format="YYYY-MM-DD"
                  defaultValue={[mr_start_time, mr_end_time]}
                  disabledDate={this.disabledDate}
                  style={{ width: 290 }}
                  onChange={(range) => {
                    this.setState({
                      rangeTmp: range,
                    });
                  }}
                />
              </div>
            </div>
          </div>
        </section>
        <section className={`${prefix}-mr-review ${prefix}-card`}>
          <div className={`${prefix}-mr-review-chart`}>
            <div className="title">
              <span>
                {intl.get({
                  id: 'code-assets.projectInsight.containers.mrInfo.ReviewSubmissionRate',
                  defaultMessage: '提交评审率：',
                })}
              </span>
              <span className="number">{totalCommitsPercent}%</span>
              <span className="help">
                {intl.get({
                  id: 'code-assets.projectInsight.containers.mrInfo.Total',
                  defaultMessage: '(共',
                })}
                {total_mr.commits_count}
                {intl.get({
                  id: 'code-assets.projectInsight.containers.mrInfo.TimesSubmittedWhere',
                  defaultMessage: '次提交，其中',
                })}
                {total_mr.review_commits_count}{' '}
                {intl.get({
                  id: 'code-assets.projectInsight.containers.mrInfo.Reviewed',
                  defaultMessage: '次经过评审)',
                })}
              </span>
              <Balloon.Tooltip
                popupStyle={{
                  maxWidth: 420,
                }}
                trigger={
                  <ButtonIcon
                    name="question-line"
                    style={{ marginLeft: 4, display: 'inline-block' }}
                  />
                }
                align="t"
              >
                <div className="balloon-info-help">
                  <div className="balloon-info-help-desc">
                    {intl.get({
                      id: 'code-assets.projectInsight.containers.mrInfo.ThisReportReflectsTheReview',
                      defaultMessage: '该报表反映了改动代码的评审率和库内成员的评审活动情况。',
                    })}

                    <br />
                    {intl.get({
                      id: 'code-assets.projectInsight.containers.mrInfo.TheAboveDataHelpsYou',
                      defaultMessage:
                        '以上数据帮助你了解被改动代码行的评审率，该比率越高，代码质量越有保证，同时从发起人和评审人两个维度了解用户评审活动参与活跃度。',
                    })}
                  </div>
                </div>
              </Balloon.Tooltip>
            </div>
            <div className="chart-detail">
              <Wcontainer>
                <Wline
                  height="200"
                  config={{
                    padding: [32, 45, 32, 45],
                    legend: {
                      // align: 'right',
                    },
                    xAxis: {
                      type: 'time',
                      mask: 'YYYY-MM-DD',
                    },

                    area: true,
                    symbol: true,
                    colors: ['#64baf7', '#67ce99', '#959aeb'],
                  }}
                  data={reviewDatas}
                />
              </Wcontainer>
            </div>
          </div>
          <div className={`${prefix}-mr-review-table`}>
            <Table
              onSort={this.onPersonalCRSort}
              className={'issue-table'}
              dataSource={detail_mr || []}
              hasBorder={false}
              loading={isLoadingDetailMr}
            >
              <Table.Column
                title={intl.get({
                  id: 'code-assets.projectInsight.containers.mrInfo.Members',
                  defaultMessage: '成员',
                })}
                dataIndex="user_info"
                cell={(value, index) => {
                  if (!value) {
                    return null;
                  }
                  if (value.name === 'unknown') {
                    value.username = 'unknown';
                    value.name = (
                      <div>
                        {intl.get({
                          id: 'code-assets.projectInsight.containers.mrInfo.UnknownNotMatchingEnterpriseMembers',
                          defaultMessage: '未知（未匹配企业成员）',
                        })}
                        <Balloon.Tooltip align="t" trigger={<YunxiaoIcon type="question-line" />}>
                          {intl.get({
                            id: 'code-assets.projectInsight.containers.mrInfo.TheSubmittedEmailAddressDoes',
                            defaultMessage: '提交邮箱（email）未匹配任何企业成员主邮箱',
                          })}
                          <a
                            href={docs('howCanCodeContributionsBe')}
                            target="_blank"
                            rel="noreferrer"
                          >
                            {intl.get({
                              id: 'code-assets.projectInsight.containers.mrInfo.HowDoISetThis',
                              defaultMessage: '如何设置才能被统计？',
                            })}
                          </a>
                        </Balloon.Tooltip>
                      </div>
                    );
                  }
                  return (
                    <div className="user-info-cell">
                      <div className={`avatar ${index === 0 ? 'active' : ''}`}>
                        {value.username !== 'unknown' ? (
                          <img src={value.avatar_url} alt="" />
                        ) : (
                          <div className={index === 0 ? '' : 'avatar-known'}>
                            {intl.get({
                              id: 'code-assets.projectInsight.containers.mrInfo.Not',
                              defaultMessage: '未',
                            })}
                          </div>
                        )}
                      </div>
                      <div>{value.name || ''}</div>
                    </div>
                  );
                }}
              />

              <Table.Column
                title={
                  <Balloon.Tooltip
                    trigger={
                      <span>
                        {intl.get({
                          id: 'code-assets.projectInsight.containers.mrInfo.ReviewSubmissionRate.1',
                          defaultMessage: '提交评审率',
                        })}
                      </span>
                    }
                    align="t"
                  >
                    {intl.get({
                      id: 'code-assets.projectInsight.containers.mrInfo.ReviewedSubmittedTimesTotalSubmitted',
                      defaultMessage: '经过评审的提交次数 / 总提交次数',
                    })}
                  </Balloon.Tooltip>
                }
                sortable
                cell={(value, index, record) => {
                  return (
                    <span>
                      {record.total_commits_count === 0
                        ? 0
                        : Math.round(
                            (record.review_commits_count / record.total_commits_count) * 100,
                          )}
                      % ( {record.review_commits_count} / {record.total_commits_count} )
                    </span>
                  );
                }}
                dataIndex="commitRate"
              />

              <Table.Column
                title={
                  <Balloon.Tooltip
                    trigger={
                      <span>
                        {intl.get({
                          id: 'code-assets.projectInsight.containers.mrInfo.LineReviewRate',
                          defaultMessage: '行评审率',
                        })}
                      </span>
                    }
                    align="t"
                  >
                    {intl.get({
                      id: 'code-assets.projectInsight.containers.mrInfo.NumberOfReviewedModifiedRows',
                      defaultMessage: '经过评审的改动行数 / 总改动行数数',
                    })}
                  </Balloon.Tooltip>
                }
                sortable
                cell={(value, index, record) => {
                  return (
                    <span>
                      {record.total_lines_count === 0
                        ? 0
                        : Math.round((record.review_lines_count / record.total_lines_count) * 100)}
                      % ( {record.review_lines_count} / {record.total_lines_count} )
                    </span>
                  );
                }}
                dataIndex="lineRate"
              />

              <Table.Column
                title={
                  <Balloon.Tooltip
                    trigger={
                      <span>
                        {intl.get({
                          id: 'code-assets.projectInsight.containers.mrInfo.NumberOfReviewsInitiated',
                          defaultMessage: '发起评审个数',
                        })}
                      </span>
                    }
                    align="t"
                  >
                    {intl.get({
                      id: 'code-assets.projectInsight.containers.mrInfo.NumberOfReviewsCreated',
                      defaultMessage: '创建的评审个数',
                    })}
                  </Balloon.Tooltip>
                }
                sortable
                dataIndex="submit_review_count"
              />

              <Table.Column
                title={
                  <Balloon.Tooltip
                    trigger={
                      <span>
                        {intl.get({
                          id: 'code-assets.projectInsight.containers.mrInfo.NumberOfReviewsParticipated',
                          defaultMessage: '参与评审次数',
                        })}
                      </span>
                    }
                    align="t"
                  >
                    {intl.get({
                      id: 'code-assets.projectInsight.containers.mrInfo.TheNumberOfReviewActivities',
                      defaultMessage: '进行评审活动的次数，同一个评审不同日期的评审行为将累计次数',
                    })}
                  </Balloon.Tooltip>
                }
                sortable
                dataIndex="participate_review_count"
              />

              <Table.Column
                title={
                  <Balloon.Tooltip
                    trigger={
                      <span>
                        {intl.get({
                          id: 'code-assets.projectInsight.containers.mrInfo.AverageResponseTime',
                          defaultMessage: '平均响应时间',
                        })}
                      </span>
                    }
                    align="t"
                  >
                    {intl.get({
                      id: 'code-assets.projectInsight.containers.mrInfo.TheTimeDifferenceBetweenThe',
                      defaultMessage: '受邀加入评审至首次评论或通过的时间差值',
                    })}
                  </Balloon.Tooltip>
                }
                sortable
                cell={(value) => {
                  return utils.formatSecondToDate(value);
                }}
                dataIndex="review_latency"
              />
            </Table>
          </div>
        </section>
        {comment_summary && (
          <section className={`${prefix}-mr-comment ${prefix}-card`}>
            <div className="title">
              <span>
                {intl.get({
                  id: 'code-assets.projectInsight.containers.mrInfo.ThousandsOfCodeComments',
                  defaultMessage: '千行代码评论数：',
                })}
              </span>
              <span className="number">
                {' '}
                {comment_summary.line_count
                  ? Math.round(
                      (comment_summary.comment_count / comment_summary.line_count) * 100000,
                    ) / 100
                  : 0}
              </span>
              <span className="help">
                {intl.get({
                  id: 'code-assets.projectInsight.containers.mrInfo.Total',
                  defaultMessage: '(共',
                })}
                {comment_summary.line_count}
                {intl.get({
                  id: 'code-assets.projectInsight.containers.mrInfo.RowChangesIncluding',
                  defaultMessage: '行改动，其中包含',
                })}{' '}
                {comment_summary.comment_count}
                {intl.get({
                  id: 'code-assets.projectInsight.containers.mrInfo.Comments.1',
                  defaultMessage: '个评论)',
                })}
              </span>
              <Balloon.Tooltip
                popupStyle={{
                  maxWidth: 440,
                }}
                trigger={
                  <ButtonIcon
                    name="question-line"
                    style={{ marginLeft: 4, display: 'inline-block' }}
                  />
                }
                align="t"
              >
                <div className="balloon-info-help">
                  <div className="balloon-info-help-desc">
                    {intl.get({
                      id: 'code-assets.projectInsight.containers.mrInfo.ThisReportReflectsTheNumber',
                      defaultMessage: '该报表反映了代码库每改动1000行代码，其中被评审的评论数。',
                    })}

                    <br />
                    {intl.get({
                      id: 'code-assets.projectInsight.containers.mrInfo.TheAboveDataCanHelp',
                      defaultMessage:
                        '以上数据可以帮助你评估改动代码的质量，和库成员评审活动的参与度。',
                    })}
                  </div>
                </div>
              </Balloon.Tooltip>
            </div>
            <div className="chart-detail">
              <Wcontainer>
                <Wlinebar
                  height="200"
                  config={{
                    xAxis: {
                      type: 'timeCat',
                      mask: 'YYYY-MM-DD',
                    },

                    yAxis: [{}, {}],
                    stack: true,
                    legend: {
                      allowAllCanceled: true,
                    },

                    padding: [32, 60, 32, 45],
                    colors: ['#64baf7', '#67ce99', '#959aeb'],
                  }}
                  data={commentData}
                />
              </Wcontainer>
            </div>
          </section>
        )}
      </div>
    );
  }
}
